/**
 * @description: 初始化插件配置
 * @cb  回调
 * @return {*}
 */
async function init(callback) {
  await sendRunTimeMessage('default')
  const token = JSON.parse(localStorage.getItem("APP-TOKEN"));
  if(!token) return false
  globalData.token = token
  const currentTabUrl = getCurrentTabUrl()
  if(!currentTabUrl) return false
  if(await getLoginInfoFn()) return false
  if (currentTabUrl && token) {
    setSinglePageVisit(currentTabUrl).then(isNotRepeat => {
      if(isNotRepeat){
        setClientId().then(res => {
          injectJs("scripts/inject.js", async () => {
            await sendRunTimeMessage('deploy')
            callback && callback();
            return true
          });
        })
      }
    })
  } else {
    return false;
  }
}


/**
 * @description: 设置用户登陆信息
 * @return {*}
 */
function getLoginInfoFn(){
  return new Promise((resolve, reject) => {
    getLoginInfo().then(res => {
      const {code, data, message} = res
      if(code === 0){
        const {expire_time, account_id} = data
        if(expire_time){
          globalData.account_id = account_id
          const expire_time_tamp = new Date(expire_time).getTime()
          globalData.expire_time_tamp = expire_time_tamp
          const expire_flag = expire_time_tamp < Date.now()
          if(expire_flag) toastMessage('error', '您的账号已过期，请联系客服')
          resolve(expire_flag)
        }else{
          toastMessage('error', '账号异常，请重试')
          resolve(true)
        }
      }else{
        toastMessage('error', message || '账号异常，请重试')
        resolve(true)
      }
    }).catch(err => resolve(true))
  })
}


/**
 * @description: 设置client_id
 * @return {*}
 */
function setClientId(){
  return new Promise(resolve => {
    chrome.storage.local.get("client_id", res => {
      let {client_id} = res
      if(!client_id){
        client_id = Math.random().toString(36).slice(-10) || Math.random().toString(36).slice(-10)
      }
      globalData.client_id = client_id
      chrome.storage.local.set({client_id}, () => resolve(true))
    })
  })
}


/**
 * @description: 判断当前tab页是否为复制页面
 * @url   插件可用url
 * @return {*}
 */
function setSinglePageVisit(url){
  return new Promise(resolve => {
    chrome.storage.local.get("currentTabId", res => {
      const {currentTabId} = res
      sendRunTimeMessage({type: "inspectSinglePage", tabId: Number(currentTabId), url}, tabId => {
        if(tabId){
          chrome.storage.local.set({currentTabId: tabId}, () => resolve(true))
          globalData.currentTabId = Number(tabId)
        }else{
          globalData.currentTabId = 0
          resolve(false)
        }
      })
    })
  })
}


/**
 * @description: 注入js
 * @param {*} jsPath  注入js路径
 * @param {*} callback  回调
 * @return {*}
 */
function injectJs(jsPath, callback) {
  jsPath = jsPath || "scripts/inject.js";
  var temp = document.createElement("script");
  temp.setAttribute("type", "text/javascript");
  temp.src = chrome.runtime.getURL(jsPath);
  temp.onload = function () {
    callback && callback();
    this.parentNode.removeChild(this);
  };
  document.body.appendChild(temp);
}


/**
 * @description: 获取插件信息
 * @return {*}
 */
function getPuginStatisticalData() {
  return new Promise(resolve => {
    const local_data = { 'total_order_full': 0, 'total_goods_full': 0, 'total_order_increment': 0, 'total_goods_increment': 0, 'today_order_full': 0, 'today_goods_full': 0, 'today_order_increment': 0, 'today_goods_increment': 0 }
    chrome.storage.local.get(local_data, res => {
      const {total_order_full, total_goods_full, total_order_increment, total_goods_increment, today_order_full, today_goods_full, today_order_increment, today_goods_increment} = res
      statisticsData.total_order_full = Number(total_order_full)
      statisticsData.total_goods_full = Number(total_goods_full)
      statisticsData.total_order_increment = Number(total_order_increment)
      statisticsData.total_goods_increment = Number(total_goods_increment)
      statisticsData.today_order_full = Number(today_order_full)
      statisticsData.today_goods_full = Number(today_goods_full)
      statisticsData.today_order_increment = Number(today_order_increment)
      statisticsData.today_goods_increment = Number(today_goods_increment)
      resolve(res)
    })
  })
}


/**
 * @description: 获取插件信息
 * @return {*}
 */
function getPluginInfo() {
  return new Promise(resolve => {
    const local_data = { 'channel': 3, 'retail_shop_id': '', 'external_shop_id': '', 'shop_name': '', 'external_shop_account': '', 'app_key': '', 'app_secret': '' }
    chrome.storage.local.get(local_data, res => {
      const {channel, retail_shop_id, external_shop_id, shop_name, external_shop_account, app_key, app_secret} = res
      pluginInfo.channel = Number(channel)
      pluginInfo.retail_shop_id = retail_shop_id
      pluginInfo.external_shop_id = external_shop_id
      pluginInfo.shop_name = shop_name
      pluginInfo.external_shop_account = external_shop_account
      pluginInfo.app_key = app_key
      pluginInfo.app_secret = app_secret
      globalData.channel = Number(channel)
      globalData.shop_name = shop_name
      globalData.shop_logo_path = channel ? tabTypes.find(item => item.channel === Number(channel)).logoPath : ''
      resolve(res)
    })
  })
}

/**
 * @description: 获取最近同步日期
 * @return {*}
 */
function getSyncDateFn(){
  return new Promise(resolve => {
    const local_data = {"recently_sync_date_order": '', "recently_sync_date_goods": ''}
    chrome.storage.local.get(local_data, res => {
      const {recently_sync_date_order, recently_sync_date_goods} = res
      recentlySyncDate.recently_sync_date_order = recently_sync_date_order
      recentlySyncDate.recently_sync_date_goods = recently_sync_date_goods
      resolve(true)
    })
  })
}


/**
 * @description: 开启增量轮巡
 * @return {*}
 */
function startMainLoop() {
  chrome.storage.local.set({isLoop: 1}, () => {
    $('#overlay').remove()
    showLooping()
    // 调试
    startIncrementSyncOrders()
    startIncrementSyncGoods()
  })
}

/**
 * @description: 开启增量订单同步
 * @return {*}
 */
function startIncrementSyncOrders(){
  incrementSyncOrdersFn()
}

/**
 * @description: 开启增量商品同步
 * @return {*}
 */
function startIncrementSyncGoods(){
  incrementSyncGoodsFn()
}



/**
 * @description: 增量订单同步 轮巡
 * @return {*}
 */
function incrementSyncOrdersFn(){
  const incrementSyncOrdersInstance = new SyncIncrementData(getIncrementOrdersList, syncOrdersBath, 1)
  incrementSyncOrdersInstance.launch()
}



/**
 * @description: 增量商品同步 轮巡
 * @return {*}
 */
function incrementSyncGoodsFn(){
  const incrementSyncGoodsInstance = new SyncIncrementData(getIncrementGoodsList, syncGoods, 2)
  incrementSyncGoodsInstance.launch()
}



/**
 * @description: 历史订单同步 轮巡
 * @return {*}
 */
function historySyncOrdersFn(){
  const order_time = ['', getDateLocaleString()]
  const historySyncOrdersInstance = new SyncHistoricalData(getHisOrdersList, syncOrdersBath, 1, order_time)
  historySyncOrdersInstance.launch().then()
}


/**
 * @description: 历史商品同步 轮巡
 * @return {*}
 */
function historySyncGoodsFn(){
  const order_time = ['', getDateLocaleString()]
  const historySyncGoodsInstance = new SyncHistoricalData(getHisGoodsList, syncGoods, 2, order_time)
  historySyncGoodsInstance.launch().then()
}


/**
 * @description: 获取表单数据
 * @param {*} data  获取到的数据
 * @cb  回调
 * @return {*}
 */
function getFormData(data, cb) {
  const {channel, retail_shop_id, external_shop_id, shop_name, external_shop_account, app_key, app_secret} = data;
  chrome.storage.local.set(data, () => {
    pluginInfo.channel = Number(channel)
    pluginInfo.retail_shop_id = retail_shop_id
    pluginInfo.external_shop_id = external_shop_id
    pluginInfo.shop_name = shop_name
    pluginInfo.external_shop_account = external_shop_account
    pluginInfo.app_key = app_key
    pluginInfo.app_secret = app_secret
    globalData.channel = Number(channel)
    globalData.shop_name = shop_name
    cb && cb()
  })
}

/**
 * @description: 表单change事件
 * @param {*} data  表单数据
 * @return {*}
 */
function changeFormFn(data){
  return new Promise(resolve => {
    chrome.storage.local.set(data, () => resolve(true))
  })
}

/**
 * @description: 连接测试逻辑
 * @data  表单数据
 * 1、数据存储
 * 2、链接测试
 * @return {*}
 */
function connectClickFn(data){
  return new Promise(resolve => {
    globalData.isConnected = true
    getFormData(data, () => {
      const {app_key, app_secret, external_shop_account} = data
      const {sign, timestamp} = getReqParam(app_key, app_secret, data)
      const params = {...data, sign, timestamp}
      // 处理连接测试结果
      verification(params).then(res => {
        if(res){
          const {code, msg} = res
          if(code === 0){
            if(globalData.account_id === external_shop_account){
              globalData.connectStatus = true
              globalData.connectErrMsg = ''
              resolve(res)
            }else{
              globalData.connectStatus = false
              globalData.connectErrMsg = '淘宝账号名不匹配'
              // 调试
              resolve(false)
              // resolve(res)
            }
          }else{
            globalData.connectStatus = false
            globalData.connectErrMsg = msg
            // 调试
            resolve(false)
            // resolve(true)
          }
        }else{
          resolve(false)
        }
      })
    })
  })
}

/**
 * @description: 点击运行后的处理逻辑
 * @data  表单数据
 * 1、链接测试
 * 2、开启运行
 * @return {*}
 */
function launchClickFn(data){
  return new Promise(resolve => {
    connectClickFn(data).then(async res => {
      if(res){
        await getSyncDateFn()
        await launchFn()
        resolve(res)
      }else{
        resolve(false)
      }
    })
  })
}


/**
 * @description: 启动
 * @return {*}
 */
function launchFn() {
  globalData.isLooping = true
  // 调试
  globalData.loopStatus = true
  // globalData.loopStatus = false
  globalData.loopingMsg = '运行中'
  globalData.pluginStartTime = getDateLocaleString()
  const local_data = {"loopingStartTime": "", "account_id": ""}
  return new Promise(resolve => {
    chrome.storage.local.get(local_data, async res => {
      let {loopingStartTime, account_id} = res
      if(!loopingStartTime){
        loopingStartTime = getDateLocaleString()
        await chrome.storage.local.set({loopingStartTime})
      }
      globalData.loopingStartTime = loopingStartTime
      if(account_id !== globalData.account_id){
        await chrome.storage.local.set({account_id: globalData.account_id})
        await clearLocalStorageData()
      }
      startMainLoop();
      resolve(true)
    })
  })
}


/**
 * @description: 停止
 * @return {*}
 */
 function stopFn() {
  $('#stopLoop').click()
}



/**
 * @description: 接收inject的信息，结束脚本运行
 * @return {*}
 */
window.addEventListener(
  "message",
  function (e) {
    if (e.data.bbtPluginHandle === "stop_") {
      stopConfirmFn()
    }else if(e.data.bbtPluginHandle === "stopLoop_"){
      stopLoopFn()
    }else if(e.data.bbtPluginHandle === "closeConfirm_"){
      closeConfirmFn()
    }else if(e.data.bbtPluginHandle === "syncHisOrders_"){  // 同步历史订单
      setBtnStatus(1, 2)
      historySyncOrdersFn()
    }else if(e.data.bbtPluginHandle === "syncHisGoods_"){  // 同步历史商品
      setBtnStatus(2, 2)
      historySyncGoodsFn()
    }
  },
  false
);

/**
 * @description: 停止沦陷
 * @return {*}
 */
function stopLoopFn(){
  chrome.storage.local.remove("isLoop", () => {
    window.history.go(0)
  })
}

/**
 * @description: 关闭确认框
 * @return {*}
 */
function closeConfirmFn(){
  $('#overlay_confirm').remove()
}

/**
 * @description: 自动启动插件
 * @return {*}
 */
function autoLaunch(){
  chrome.storage.local.get("isLoop", (res) => {
    if(res.isLoop){
      getPuginStatisticalData().then(() => {
        getPluginInfo().then(res => launchClickFn(res))
      })
    }
  })
}

/**
 * @description: 监听
 * @return {*}
 */
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  const { type, data } = message;
  switch (type) {
    case "getPuginStatisticalData":
      getPuginStatisticalData().then(res => sendResponse(res))
      break;
    case "getPluginInfo":
      getPluginInfo().then(res => sendResponse(res))
      break;
    case "getPluginStatus":
      sendResponse(globalData);
      break;
    case "change":
      changeFormFn(data).then(res => sendResponse(res))
      break;
    case "connect":
      connectClickFn(data).then(res => sendResponse(res))
      return true
    case "launch_":
      launchClickFn(data).then(res => sendResponse(res))
      break;
    case "stop_":
      stopFn()
      sendResponse(true)
      break;
    case 'init_':
      init(() => autoLaunch())
      break;
  }
  return true;
});




// 和background中的init有冲突，暂时先注释掉

/**
 * @description: dom加载完成
 */
// document.addEventListener("DOMContentLoaded", () => {
//   console.log('DOMContentLoaded DOMContentLoaded DOMContentLoaded')
//   init(() => autoLaunch());
// });
